use std::{
    env,
    thread,
    io::{ prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};
//请求与响应函数
fn handle_connection(mut stream: TcpStream) {
    let port = set_port();
    let buf_reader = BufReader::new(&mut stream);
    let req: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();
    println!("获取服务端头行请求: {}", req.split_first().unwrap().0);
    //服务端响应文本至前端
    let (status_line, content) = if req[0].starts_with("GET") {
        ("HTTP/1.1 200 OK\r\n\r\n", format!("HTTP methods are {},Accessible port:{}",req[0],port))
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", format!("HTTP methods are {},But accessible port:{}",req[0],port))
    };
    let res = format!("{}\r\n\r\nResponse content:{}\r\n\r\n", status_line, content);
    stream.write_all(res.as_bytes()).unwrap();
    stream.flush().unwrap();
}
//设置端口
fn set_port() -> u16 {
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 {
        args[1].parse().expect("Please provide a valid port number. The default is 7878")
    } else {
        7878
    }
}
fn main() {
    let port = set_port();
    //ipv4
    // let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).unwrap();
    // for stream in listener.incoming() {
    //     let stream = stream.unwrap();
    //     println!("Connection from {} established", stream.peer_addr().unwrap());
    //     handle_connection(stream);
    // }
    //ipv4/ipv6
    let ipv4_listener = TcpListener::bind(format!("0.0.0.0:{}", port)).unwrap();
    let ipv6_listener = TcpListener::bind(format!("::1:{}", port)).unwrap();
    for listener in vec![ipv4_listener, ipv6_listener] {
        thread::spawn(move || {
            for stream in listener.incoming() {
                match stream {
                    Ok(stream) => {
                        thread::spawn(move|| {
                            println!("Connection from {} established!", stream.peer_addr().unwrap());
                            handle_connection(stream);
                        });
                    }
                    Err(e) => {
                        eprintln!("Error accepting stream: {}", e);
                    }
                }

            }
        });
    }
    let _ =thread::park();
}
